package party.eggtart.calculaxenumer;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TypeA_Activity extends AppCompatActivity {

    XUniverse universe = new XUniverse();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_type_a_);

        Button Button_Kill = (Button) findViewById(R.id.button),
                Button_Clear = (Button) findViewById(R.id.button2);

        final EditText et = (EditText) findViewById(R.id.editText);

        assert Button_Kill != null;
        Button_Kill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    String szInput[] =et.getText().toString().split(" ");

                int len = szInput.length, rlen = len;

                if(len <= 1) {
                    Toast.makeText(TypeA_Activity.this, "数列长度不合法", Toast.LENGTH_SHORT).show(); return;
                }

                ArrayList<String> szUser = new ArrayList<>(len),
                        szOrdered = new ArrayList<>(len);

                try {

                    for (int i = 0; i < len; i++) // 排入szUser
                    {
                        String tmp[] = szInput[i].split(",");
                        int nRepeat = 1;
                        if (tmp.length != 1) {
                            int Repeating = Integer.valueOf(tmp[1]);
                            nRepeat = Repeating;
                            rlen += Repeating - 1;
                        }
                        for (int c = 1; c <= nRepeat; c++) {
                            szUser.add(tmp[0]);
                        }
                    }
                } catch (IndexOutOfBoundsException e)
                {
                    MessageBox("Error: IndexOutOfBoundsException\n\n数组越界。", "好的吧...", TypeA_Activity.this);
                    e.printStackTrace();
                    return;
                }
                  catch (NumberFormatException e)
                {
                    MessageBox("Error: NumberFormatException\n\n遇到非法字符。", "好的吧...", TypeA_Activity.this);
                    e.printStackTrace();
                    return;
                }

               for(int i = 0; i < rlen; ) // 升序排列
               {
                    double min = Double.valueOf(szUser.get(i));
                    int IndexOfMin = i;
                   for(int c=0; c<rlen; c++)
                   {
                       double cur = Double.valueOf(szUser.get(c));
                       if(min > cur)
                       {
                           min = cur;
                           IndexOfMin = c;
                       }
                   }
                   szUser.remove(IndexOfMin);
                   rlen--;
                   szOrdered.add(String.valueOf(min));
               }

                double dwMin = Double.valueOf(szOrdered.get(0)),
                        dwMax = Double.valueOf(szOrdered.get(szOrdered.size() - 1)),
                        dwTotal = 0,
                        dwAverage = 0,
                        dwMaxsub = 0,
                        dwVariance = 0,
                        dwVariancepow = 0,
                        dwMiddleNumber = 0;

                ArrayList<String> szMode = new ArrayList<>(0);

                int nHighestCount = 0;

                // 排列 & 总数
                String Enumed = "";
                for(int i=0; i<szOrdered.size(); i++)
                {
                    double cur = Double.valueOf(szOrdered.get(i));
                    dwTotal = sum(cur, dwTotal);
//                 dwTotal += cur;
                    Enumed += szOrdered.get(i) + "  ";
                }

                // 平均数
//                dwAverage = dwTotal / szOrdered.size();
                dwAverage = div(dwTotal, szOrdered.size(), 2);

                // 极差
//                dwMaxsub = dwMax - dwMin;
                dwMaxsub = sub(dwMax, dwMin);

                // 方差
                double tmp = 0;
                for(int i=0; i<szOrdered.size(); i++)
                {
                    double cur = Double.valueOf(szOrdered.get(i));
                    tmp = sum(Math.pow(cur - dwAverage, 2), tmp);
//                    tmp += Math.pow(cur - dwAverage, 2);
                }
                    tmp = div(tmp, szOrdered.size(), 2);
//                    tmp /= szOrdered.size();
                    dwVariance = tmp;

                // 标准差
                    dwVariancepow = Math.pow(dwVariance, 0.5);

                // 中位数
                int MiddleIndex = 0;
                    if((double)(int)(szOrdered.size() / 2d) != (szOrdered.size() / 2d))
                    {
                        MiddleIndex = (int)Math.ceil(szOrdered.size() / 2d);
                        dwMiddleNumber = Double.valueOf(szOrdered.get(MiddleIndex - 1));

                    } else {
                        MiddleIndex = szOrdered.size() / 2;
                        dwMiddleNumber = div(sum( Double.valueOf(szOrdered.get(MiddleIndex - 1)), Double.valueOf(szOrdered.get(MiddleIndex)) ),2,2);
                    }

                // 众数
                Map<Double, Double> map=new HashMap<>();
                for(int i=0;i<szOrdered.size();i++){
                    if((map.get(Double.valueOf(szOrdered.get(i)))) == null){
                        map.put(Double.valueOf(szOrdered.get(i)), 1.0);
                    }
                    else{
                        double num = map.get(Double.valueOf(szOrdered.get(i)));
                        map.put(Double.valueOf(szOrdered.get(i)), num + 1f);
                    }
                }

                    for (double num : map.keySet()
                            ) {

                        double max = map.get(num);

                        for(double c : map.keySet())
                        {
                            double cur = map.get(c);
                            if(max < cur) {
                                max = cur;
                            }
                        }

                        nHighestCount = (int)max;


                        for(double c : map.keySet())
                        {
                            double cur = map.get(c);
                            if(cur == max && !szMode.contains(String.valueOf(c))) {
                                szMode.add(String.valueOf(c));
                            }
                        }
                }


                // 众数输出
                String ModeEnum = "", Addition = "";
                for(int i = 0; i < szMode.size(); i++) {
                    ModeEnum += szMode.get(i) + "  ";
                }
                if(szMode.size() > 1) {
                    Addition = "各";
                }

                String FinalOutput = "";
                FinalOutput += "升序排列结果:\n" + Enumed
                        + "\n\n总值:\n" + String.valueOf(dwTotal) + " "
                        + "\n\n平均值:\n" + String.valueOf(dwAverage) + " "
                        + "\n\n方差:\n" + String.valueOf(dwVariance) + " "
                        + "\n\n标准差:\n" + String.valueOf(dwVariancepow) + " "
                        + "\n\n最值:\n" + String.valueOf(dwMin) + " / " + String.valueOf(dwMax) + " "
                        + "\n\n极差:\n" + String.valueOf(dwMaxsub) + " "
                        + "\n\n中位数:\n" + String.valueOf(dwMiddleNumber) + " "
                        + "\n\n众数:\n" + ModeEnum + " (" + Addition + "出现 " + String.valueOf(nHighestCount) + " 次)";


                FinalOutput = FinalOutput.replace(".0 "," ");
                MessageBox(FinalOutput, "知道啦", TypeA_Activity.this);
                /*
                AlertDialog.Builder adb = new AlertDialog.Builder(TypeA_Activity.this);
                adb.setMessage(FinalOutput)
                        .show();*/

            }
        });

        assert Button_Clear != null;
        Button_Clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et.setText("");
            }
        });

    }

    public static double round(double value, int scale,
                               int roundingMode) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(scale, roundingMode);
        double d = bd.doubleValue();
        bd = null;
        return d;
    }

    public double sum(double d1,double d2){
        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.add(bd2).doubleValue();
    }

    public double sub(double d1,double d2){
        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.subtract(bd2).doubleValue();
    }

    public double mul(double d1,double d2){
        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.multiply(bd2).doubleValue();
    }

    public double div(double d1,double d2,int scale){
        //  当然在此之前，你要判断分母是否为0，
        //  为0你可以根据实际需求做相应的处理

        BigDecimal bd1 = new BigDecimal(Double.toString(d1));
        BigDecimal bd2 = new BigDecimal(Double.toString(d2));
        return bd1.divide
                (bd2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    public void MessageBox(CharSequence Message, CharSequence ButtonName, Context context)
    {
        universe.MessageBox(Message, ButtonName, context);
        /*
        AlertDialog.Builder adb = new AlertDialog.Builder(context);
        adb.setMessage(Message)
                .setPositiveButton(ButtonName, null)
                .show();
                */
    }


}
